package digital.store.springmvc.controller;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import digital.store.springmvc.service.CategoryService;
import digital.store.springmvc.service.OrderService;
import digital.store.springmvc.service.ProductService;
import digital.store.tutorial.springmvc.model.Category;
import digital.store.tutorial.springmvc.model.Orderk;
import digital.store.tutorial.springmvc.model.Product;
import digital.store.tutorial.springmvc.model.ShoppingCart;

@Controller
@RequestMapping(value={"/home/shoppingcart","/product-detail/shoppingcart/"})
public class ShoppingController {
	
	public ShoppingCart cart = new ShoppingCart() ;

	@Autowired
	private ProductService productService;
	@Autowired
	private CategoryService categoryService;
	
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public String addCart(@PathVariable Long id, Model model,HttpSession session) {
		Collection<Category> categories = categoryService.findAll();
		Product product = productService.findById(id);
		Collection<Product> products = productService.findByCategoryId(product.getCategory().getId());
		Category category = product.getCategory();
		if ( session.getAttribute("user")!= null)
		{
			cart.setTotal(cart.getTotal() + product.getPrice());
			cart.setProduct(product);
			session.setAttribute("mycart", cart);
		}
		model.addAttribute("products",products);
	    model.addAttribute("category", category);
	    model.addAttribute("categoriesSidebar", categories);
		return "redirect:/home/"+category.getId().toString();
    }
}
